﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.DeviceManage.Project;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage.Project
{
    /// <summary>
    /// 删除项目维护信息处理器
    /// </summary>
    public class DeleteProjectMaintenanceHandler : IRequestHandler<DeleteProjectMaintenanceCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProjectMaintenance> _projectMaintenanceRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectMaintenanceRepository">项目维护仓储接口</param>
        /// <param name="mapper">对象映射器</param>
        public DeleteProjectMaintenanceHandler(IBaseRespository<ProjectMaintenance> projectMaintenanceRepository, IMapper mapper)
        {
            _projectMaintenanceRepository = projectMaintenanceRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理删除项目维护命令
        /// </summary>
        /// <param name="request">删除项目维护命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含操作结果的ApiResult</returns>
        public async Task<ApiResult<int>> Handle(DeleteProjectMaintenanceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID获取项目维护数据
                var projectMaintenance = await _projectMaintenanceRepository.GetModelAsync(request.Id);
                if (projectMaintenance == null)
                {
                    // 项目维护不存在时返回错误信息
                    return new ApiResult<int>
                    {
                        Msg = "项目维护不存在",
                        Code = ApiEnum.Failed
                    };
                }

                // 执行软删除（标记Isdel为true）
                projectMaintenance.Isdel = true;
                await _projectMaintenanceRepository.Update(projectMaintenance);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = projectMaintenance.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除项目维护时发生错误: {ex.Message}"
                };
            }
        }
    }
}
